<template>
  <div class="wapper">
    <div class="box">
      <div class="content">
        <h2>注册</h2>
        <form @submit.prevent="handleRegister">
          <!-- 表单部分 -->
          <div>
            <input type="text" placeholder="用户名" v-model="username" />
          </div>
          <div>
            <input type="password" placeholder="密码" v-model="password" />
          </div>
          <div>
            <input type="email" placeholder="邮箱" v-model="email" />
          </div>
          <div>
            <input type="submit" value="注册" />
          </div>
        </form>
        <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
      </div>
      <a href="/login" class="btns">返回登录</a>

      <!-- 自定义成功弹窗 -->
      <transition name="modal-fade">
        <div v-if="showSuccessModal" class="modal-overlay">
          <div class="modale">
            <h3>注册成功</h3>
            <p class="my-4">{{ successMessage }}</p>
            <!-- 按钮右对齐 -->
            <div class="text-end">
              <button class="modal-button" @click="redirectToLogin">
                确定并返回登录
              </button>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>
  
  <script>
import axios from "axios";

export default {
  data() {
    return {
      username: "",
      password: "",
      email: "",
      errorMessage: "",
      successMessage: "",
      showSuccessModal: false, // 控制弹窗显示
    };
  },
  methods: {
    async handleRegister() {
      this.errorMessage = "";
      this.successMessage = "";

      // 简单的表单验证
      if (!this.username) {
        this.errorMessage = "请输入账号。";
        return;
      }

      if (!this.password) {
        this.errorMessage = "请输入密码。";
        return;
      }

      if (!this.email) {
        this.errorMessage = "请输入邮箱。";
        return;
      }

      const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
      if (!passwordRegex.test(this.password)) {
        this.errorMessage = "密码必须至少包含 8 个字符，包括字母和数字。";
        return;
      }

      try {
        // 向后端发送注册请求
        const response = await axios.post(
          "http://localhost:8000/api/register/",
          {
            username: this.username,
            password: this.password,
            email: this.email,
          }
        );

        // 显示成功消息
        this.successMessage = response.data.message || "注册成功！";
        this.showSuccessModal = true; // 显示弹窗
      } catch (error) {
        this.errorMessage = error.response?.data?.error || "注册失败";
      }
    },
    redirectToLogin() {
      this.showSuccessModal = false;
      this.$router.push("/login");
    },
  },
};
</script>
<style src="../../assets/css/home.css" scoped></style>